<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\admin\model\RouteModel;
use cmf\controller\AdminBaseController;
use app\portal\model\PortalCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;
use tree\Tree;

class AdminCategoryController extends AdminBaseController
{
    /**
     * 文章分类列表
     * @adminMenu(
     *     'name'   => '分类管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章分类列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {   
        $portalCategoryModel = new PortalCategoryModel();
        $categoryTree        = $portalCategoryModel->adminCategoryTableTree();

        $this->assign('category_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 添加文章分类
     * @adminMenu(
     *     'name'   => '添加文章分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章分类',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $parentId            = $this->request->param('parent', 0, 'intval');
        $portalCategoryModel = new PortalCategoryModel();
        $categoriesTree      = $portalCategoryModel->adminCategoryTree($parentId);

        $themeModel        = new ThemeModel();
        $listThemeFiles    = $themeModel->getActionThemeFiles('portal/List/index');
        $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');

        $where  = [
            'delete_time' => 0,
            'site_id'     => get_site_id(),
        ];
        $slide = db('Slide')->where($where)->select();
        $this->assign('slide', $slide);

        //递归查询父级分类文章缩略图推荐尺寸
        $thumbSize = get_thumb_size($parentId);
        $this->assign("thumb_size", $thumbSize);

        
        $this->assign("taxonomys", get_module());       //分类类型列表
        $this->assign("audit_list", get_audit_flow());  //审核流程列表
        
        $this->assign('list_theme_files', $listThemeFiles);
        $this->assign('article_theme_files', $articleThemeFiles);
        $this->assign('categories_tree', $categoriesTree);
        return $this->fetch();
    }

    /**
     * 添加文章分类提交
     * @adminMenu(
     *     'name'   => '添加文章分类提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章分类提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        $portalCategoryModel = new PortalCategoryModel();

        $data   = $this->request->param();
        
        $result = $this->validate($data, 'PortalCategory');

        if ($result !== true) {
            $this->error($result);
        }

        $result = $portalCategoryModel->addCategory($data);

        if ($result === false) {
            $this->error('添加失败!');
        }

        //操作日志
        admin_log($data['name'], 'add', 'article_category');

        $this->success('添加成功!', url('AdminCategory/index'));

    }

    /**
     * 编辑文章分类
     * @adminMenu(
     *     'name'   => '编辑文章分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章分类',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $category = PortalCategoryModel::get($id)->toArray();

            //递归查询父级分类文章缩略图推荐尺寸
            $category['thumb_size'] = empty($category['thumb_size']) ? get_thumb_size($id) : $category['thumb_size'] ;

            $portalCategoryModel = new PortalCategoryModel();
            $categoriesTree      = $portalCategoryModel->adminCategoryTree($category['parent_id'], $id);

            $themeModel        = new ThemeModel();
            $listThemeFiles    = $themeModel->getActionThemeFiles('portal/List/index');
            $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');

            $routeModel        = new RouteModel();
            $alias             = $routeModel->getUrl('portal/List/index', ['id' => $id]);
            $category['alias'] = $alias;
            
            //banner广告列表
            $where  = [
                'delete_time' => 0,
                'site_id'     => get_site_id(),
            ];
            $slide = db('Slide')->where($where)->select();
            $this->assign('slide', $slide);
            
            //分类类型列表
            $this->assign("taxonomys", get_module($category['taxonomy']));

            //审核流程列表
            $this->assign("audit_list", get_audit_flow($category['audit_id']));

            $this->assign($category);
            $this->assign('list_theme_files', $listThemeFiles);
            $this->assign('article_theme_files', $articleThemeFiles);
            $this->assign('categories_tree', $categoriesTree);
            return $this->fetch();
        } else {
            $this->error('操作错误!');
        }

    }

    /**
     * 编辑文章分类提交
     * @adminMenu(
     *     'name'   => '编辑文章分类提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章分类提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data = $this->request->param();

        $result = $this->validate($data, 'PortalCategory');

        if ($result !== true) {
            $this->error($result);
        }

        $portalCategoryModel = new PortalCategoryModel();

        $result = $portalCategoryModel->editCategory($data);

        if ($result === false) {

            //操作日志
            admin_log($data['name'], 'edit', 'article_category');

            $this->error('保存失败!');
        }

        $this->success('保存成功!');
    }

    /**
     * 文章分类选择对话框
     * @adminMenu(
     *     'name'   => '文章分类选择对话框',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章分类选择对话框',
     *     'param'  => ''
     * )
     */
    public function select()
    {
        //根据操作标识，获取拥有该操作权限的分类id
        $operate = $this->request->param('operate','','trim');
        
        $idList  = get_cat_priv($operate, 'portal_category'); //获取该角色可操作的栏目分类id

        $ids                 = $this->request->param('ids');
        $selectedIds         = explode(',', $ids);

        $portalCategoryModel = new PortalCategoryModel();

        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
               value='\$id' data-name='\$name' \$checked \$disabled>
    </td>
    <td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
</tr>
tpl;
       
        $categoryTree = $portalCategoryModel->adminCategoryTableTree($selectedIds, $tpl, $idList);

        $where      = ['delete_time' => 0];
        $categories = $portalCategoryModel->where($where)->select();

        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 文章分类排序
     * @adminMenu(
     *     'name'   => '文章分类排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章分类排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('portal_category'));

        //操作日志
        admin_log('', '', 'article_category_list_order');

        $this->success("排序更新成功！", '');
    }

    /**
     * 删除文章分类
     * @adminMenu(
     *     'name'   => '删除文章分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除文章分类',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $portalCategoryModel = new PortalCategoryModel();
        $id                  = $this->request->param('id');
        //获取删除的内容
        $findCategory = $portalCategoryModel->where('id', $id)->find();

        if (empty($findCategory)) {
            $this->error('分类不存在!');
        }

        $categoryChildrenCount = $portalCategoryModel->where('parent_id', $id)->count();

        if ($categoryChildrenCount > 0) {
            $this->error('此分类有子类无法删除!');
        }

        $categoryPostCount = Db::name('portal_category_post')->where('category_id', $id)->count();

        if ($categoryPostCount > 0) {
            $this->error('此分类有文章无法删除!');
        }

        $data   = [
            'object_id'   => $findCategory['id'],
            'create_time' => time(),
            'table_name'  => 'portal_category',
            'name'        => $findCategory['name'],
            'site_id'     => $findCategory['site_id'],  //站点ID
        ];
        $result = $portalCategoryModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($result) {
            Db::name('recycleBin')->insert($data);

            //操作日志
            admin_log($findCategory['name'], 'delete', 'article_category');

            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 设置要发布的栏目
     * @adminMenu(
     *     'name'   => '设置要发布的栏目',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '设置要发布的栏目',
     *     'param'  => ''
     * )
     */
    public function show()
    {
        $tree       = new Tree();
        $tree->icon = ['│ ', '├─ ', '└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $where = ['delete_time' => 0];
        $portalCategoryModel = new PortalCategoryModel();
        $result = $portalCategoryModel
               -> where($where)
               -> order("list_order", "ASC")
               -> column('');
               // -> select('id');
        // pre($result,1);

        // //重组数据
        // $categorys = [];
        // foreach ($result as $m) {
        //     $categorys[$m['id']] = $m;
        // }

        foreach ($result as $n => $t) {
            $result[$n]['checked']      = ($t['is_show']==1) ? ' checked' : '';
            $result[$n]['level']        = $this->_getLevel($t['id'], $result);
            $result[$n]['style']        = empty($t['parent_id']) ? '' : 'display:none;';
            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
        }
        // pre($result,1);

        $str = "<tr id='node-\$id'\$parentIdNode  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<label><input type='checkbox' name='ids[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</label></td>
                </tr>";
        $tree->init($result);

        $category = $tree->getTree(0, $str);

        $this->assign("category", $category);

        return $this->fetch();
    }

    /**
     * 设置要发布的栏目
     * @adminMenu(
     *     'name'   => '设置要发布的栏目',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '设置要发布的栏目',
     *     'param'  => ''
     * )
     */
    public function showPost()
    {
        if ($this->request->isPost()) {
            $where  = ['delete_time' => 0];
            $where2 = ['status' => 1];

            // if (is_array($this->request->param('ids/a')) && count($this->request->param('ids/a')) > 0) {

                $ids = $this->request->param('ids/a');

                db('portal_category')->where($where)->update(['is_show'=>0]);
                $where['id'] = ['in',$ids];
                db('portal_category')->where($where)->update(['is_show'=>1]);

                db('portal_category_post')->where($where2)->update(['is_show'=>0]);
                $where2['category_id'] = ['in',$ids];
                db('portal_category_post')->where($where2)->update(['is_show'=>1]);

                admin_log('','SETTING','NEED_PORTAL_CATEGORY');
            // }

            //操作日志
            admin_log('', '', 'article_category_show');

            $this->success("保存成功！");
        }
    }

    /**
     * 获取栏目深度
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    protected function _getLevel($id, $array = [], $i = 0)
    {   
        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
            return $i;
        } else {
       
            $i++;
          
            return $this->_getLevel($array[$id]['parent_id'], $array, $i);
        }
    }
}
